package com.hunttown.mes.manage.controller._mes;

import com.hunttown.mes.common.utils.DateConvertUtils;
import com.hunttown.mes.common.utils.DateUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.rpc.domain.*;
import com.hunttown.mes.rpc.domain.enums.mes.passstation.HandleResultEnum;
import com.hunttown.mes.rpc.domain.enums.mes.passstation.HandleTypeEnum;
import com.hunttown.mes.rpc.domain.enums.mes.produce.MaterialReadyEnum;
import com.hunttown.mes.rpc.domain.enums.mes.produce.OrderStatusEnum;
import com.hunttown.mes.rpc.domain.enums.mes.produce.OrderTypeEnum;
import com.hunttown.mes.rpc.domain.enums.mes.produce.QRCodeRuleEnum;
import com.hunttown.mes.rpc.domain.query.MesProducePassStationDTOQuery;
import com.hunttown.mes.rpc.domain.query.MesProducePassStationDetailDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportPurchaseDetailDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportPurchaseOutDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.manage.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * created by wangjunfu on 2022-06-07 08:16:20
 */
@Controller
@RequestMapping(value = "/mes/passstation")
public class MesProducePassStationController {

    private final static Logger logger = LoggerFactory.getLogger(MesProducePassStationController.class);

    private final MesProducePassStationManageService mesProducePassStationService;
    private final MesProducePassStationDetailManageService mesProducePassStationDetailService;
    private final MesProducePackageManageService mesProducePackageService;
    private final MesProduceOrderManageService mesProduceOrderService;
    private final MesProduceWorkmanshipManageService mesProduceWorkmanshipService;
    private final MesProduceWorkmanshipProcessManageService mesProduceWorkmanshipProcessService;
    private final AnalysisManageManageService manageService;
    private final TransportManageDepRelManageService depRelManageService;
    private final TransportPurchaseOutManageService purchaseOutService;
    private final TransportPurchaseManageService purchaseService;
    private final TransportPurchaseDetailManageService purchaseDetailService;
    private final IotMessageManageService iotMessageService;
    private final ModelService modelService;

    @Autowired
    public MesProducePassStationController(MesProducePassStationManageService mesProducePassStationService, MesProducePassStationDetailManageService mesProducePassStationDetailService, MesProducePackageManageService mesProducePackageService, MesProduceOrderManageService mesProduceOrderService, MesProduceWorkmanshipManageService mesProduceWorkmanshipService, MesProduceWorkmanshipProcessManageService mesProduceWorkmanshipProcessService, AnalysisManageManageService manageService, TransportManageDepRelManageService depRelManageService, TransportPurchaseOutManageService purchaseOutService, TransportPurchaseManageService purchaseService, TransportPurchaseDetailManageService purchaseDetailService, IotMessageManageService iotMessageService, ModelService modelService) {
        this.mesProducePassStationService = mesProducePassStationService;
        this.mesProducePassStationDetailService = mesProducePassStationDetailService;
        this.mesProducePackageService = mesProducePackageService;
        this.mesProduceOrderService = mesProduceOrderService;
        this.mesProduceWorkmanshipService = mesProduceWorkmanshipService;
        this.mesProduceWorkmanshipProcessService = mesProduceWorkmanshipProcessService;
        this.manageService = manageService;
        this.depRelManageService = depRelManageService;
        this.purchaseOutService = purchaseOutService;
        this.purchaseService = purchaseService;
        this.purchaseDetailService = purchaseDetailService;
        this.iotMessageService = iotMessageService;
        this.modelService = modelService;
    }

    //region 订单过站

    /**
     * 订单过站
     *
     * @param model     model模型
     * @param produceId 生产订单ID
     * @param processId 过站ID（如果指定了过站ID，则取当前过站信息）
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer produceId, Integer processId) {
        processId = processId == null ? 0 : processId;

        //当前用户
        String pin = AdminBaseClass.getPin(request);
        AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

        //获取生产订单信息
        MesProduceOrderDTO produceObj = mesProduceOrderService.getById(produceId);
        if (produceObj == null) {
            throw new RuntimeException("未查询到生产订单信息");
        }
        produceObj.setShipName(modelService.getMesShipName(produceObj.getShipId()));
        produceObj.setProduceLineName(modelService.getMesProduceLineName(produceObj.getProduceLine()));
        model.addAttribute("produceObj", produceObj);

        //获取最新的一条过站信息（每道工序都会生成一条，如果指定了工序就选择此工序的）
        MesProducePassStationDTO passStationObj = mesProducePassStationService.getByProduceId(produceId, processId);

        //获取所有包列表
        String endDateSr = null;
        if (processId > 0 && passStationObj != null && passStationObj.getPassStatus() == 1) { //手动选择已过站的工序才会判断（原因是有拆包和合包）
            endDateSr = passStationObj.getOperateTimeSr();
        }
        List<MesProducePackageDTO> packageList = mesProducePackageService.getListByProduceId(produceId, endDateSr);

        //获取所有工序列表
        List<MesProduceWorkmanshipProcessDTO> processList = mesProduceWorkmanshipProcessService.getListByShipid(produceObj.getShipId());

        //region 新订单，还未有任何过站记录，那先插入一条
        if (passStationObj == null) {
            passStationObj = new MesProducePassStationDTO();
            passStationObj.setId(0);
            passStationObj.setProduceId(produceId);
            passStationObj.setShipId(produceObj.getShipId());

            //如果指定了工序，此工序还没有过站记录，那么就生成此工序的
            int _processId = processId;
            if (_processId == 0) {
                _processId = processList.size() == 0 ? 0 : processList.get(0).getId();
            }
            passStationObj.setProcessId(_processId);
            passStationObj.setProduceLine(produceObj.getProduceLine());
            passStationObj.setEquipId(0);
            passStationObj.setPassType(2);
            passStationObj.setTotalCount(produceObj.getEstimateCount());
            passStationObj.setPassCount(0);
            passStationObj.setGoodCount(0);
            passStationObj.setBadCount(0);
            passStationObj.setGoodRate(BigDecimal.ZERO);
            passStationObj.setOperator(curr_obj.getId()); //过站员默认为当前用户
            passStationObj.setDepId(depRelManageService.getDepIdByAdminId(curr_obj.getId()));
            passStationObj.setOperateTime(new Date());
            passStationObj.setPassStatus(0);
            passStationObj.setAdminId(curr_obj.getId());
            passStationObj.setCreateTime(new Date());
            passStationObj.setStopFlag(0);
            passStationObj.setDeleteFlag(0);
            passStationObj = mesProducePassStationService.insert(passStationObj);
        }
        //endregion

        //region 如果已经过站了，看当前过站是否已经过完

        //region 如果没过完，则继续过（或者手动选择了某一道工序）
        if (passStationObj.getPassStatus() == 0 || processId > 0) {

            //region 更新包中的总数量
            //包中的过站数量来源于上一条过站明细的：good_count（因为有不良品）
            for (MesProducePackageDTO item : packageList) {
                MesProducePassStationDetailDTO detailDTO = mesProducePassStationDetailService.getByProducePkg(produceId, item.getId());
                if (detailDTO != null) {
                    item.setTotalCount(detailDTO.getGoodCount());
                }
            }
            //endregion

            //region 标记已过站包
            //获取当前过站的【过站明细】
            List<MesProducePassStationDetailDTO> stationDetailList = mesProducePassStationDetailService.getListByStationId(passStationObj.getId());

            for (MesProducePassStationDetailDTO item : stationDetailList) {
                MesProducePackageDTO pkg = mesProducePackageService.getById(item.getPackageId());
                if (pkg != null) {
                    item.setPackageName(pkg.getPackageName());
                    item.setStartEndNumber(pkg.getStartNumber() + " ~ " + pkg.getEndNumber());
                }
            }

            //已过站包列表
            model.addAttribute("stationDetailList", stationDetailList);

            //已过站包ID
            List<Integer> pakIds = new ArrayList<>();
            for (MesProducePassStationDetailDTO item : stationDetailList) {
                pakIds.add(item.getPackageId());
            }

            //给已过站包一个标记
            for (MesProducePackageDTO item : packageList) {
                if (pakIds.contains(item.getId())) {
                    item.setStatus(1);
                } else {
                    item.setStatus(0);
                }
            }
            //endregion
        }
        //endregion

        //region 如果过完，过下一道工序（非手动选择，并且均已出站）
        if (passStationObj.getPassStatus() == 1 && processId == 0) {

            //是否还有下一道工序
            int nextProcess = -1;
            for (int i = 0; i < processList.size(); i++) {
                if (processList.get(i).getId().equals(passStationObj.getProcessId()) && processList.size() > i + 1) { //并且，最后一条不作判断
                    nextProcess = processList.get(i + 1).getId();
                    break;
                }
            }

            if (nextProcess > 0) {
                MesProducePassStationDTO newobj = new MesProducePassStationDTO();
                newobj.setId(0);
                newobj.setProduceId(produceId);
                newobj.setShipId(produceObj.getShipId());
                newobj.setProcessId(nextProcess);
                newobj.setProduceLine(produceObj.getProduceLine());
                newobj.setEquipId(passStationObj.getEquipId());
                newobj.setPassType(2);
                newobj.setTotalCount(passStationObj.getGoodCount());
                newobj.setPassCount(0);
                newobj.setGoodCount(0);
                newobj.setBadCount(0);
                newobj.setGoodRate(BigDecimal.ZERO);
                newobj.setOperator(curr_obj.getId()); //过站员默认为当前用户
                newobj.setDepId(depRelManageService.getDepIdByAdminId(curr_obj.getId()));
                newobj.setOperateTime(new Date());
                newobj.setPassStatus(0);
                newobj.setAdminId(curr_obj.getId());
                newobj.setCreateTime(new Date());
                newobj.setStopFlag(0);
                newobj.setDeleteFlag(0);
                newobj = mesProducePassStationService.insert(newobj);

                passStationObj = newobj;
            }
        }
        //endregion

        //endregion

        //region 标记已过站工序
        //获取所有已过站工序记录
        MesProducePassStationDTOQuery passProcessQuery = new MesProducePassStationDTOQuery();
        passProcessQuery.setProduceId(produceId);
        passProcessQuery.setStopFlag(0);
        Page<MesProducePassStationDTO> passProcessPage = mesProducePassStationService.getForPage(passProcessQuery);

        //已过站工序ID
        List<Integer> passProcessIds = new ArrayList<>();
        for (MesProducePassStationDTO item : passProcessPage.getItems()) {
            passProcessIds.add(item.getProcessId());
        }

        //是否完工
        int isComplete = 1;

        //给已过站工序一个标记
        for (MesProduceWorkmanshipProcessDTO item : processList) {
            if (passProcessIds.contains(item.getId()) || item.getId().equals(processId)) {
                //必须是过站中状态（或者手动选择了某一道工序）
                if ((item.getId().equals(passStationObj.getProcessId()) && passStationObj.getPassStatus() == 0) || item.getId().equals(processId)) {
                    item.setStatus(2); //过站中
                    isComplete = 0;
                } else {
                    item.setStatus(1); //已过站
                }

                //筛选（良品率）
                List<MesProducePassStationDTO> selectList = passProcessPage.getItems().stream().filter(s -> s.getProcessId().equals(item.getId())).collect(Collectors.toList());
                if (selectList.size() > 0) {
                    item.setGoodRate(selectList.get(0).getGoodRate());
                }

            } else {
                item.setStatus(0);     //未过站
                isComplete = 0;
            }
        }

        model.addAttribute("isComplete", isComplete);
        //endregion

        //过站信息
        passStationObj.setOperatorCn(modelService.getManageName(passStationObj.getOperator()));
        passStationObj.setOperateTime(new Date());
        passStationObj.setDepName(modelService.getDepName(passStationObj.getDepId()));
        model.addAttribute("passStationObj", passStationObj);

        //工序列表
        model.addAttribute("processList", processList);

        //包列表
        model.addAttribute("packageList", packageList);

        //缺陷类型
        modelService.getCatalogPage(model, 34, "defectTypeList");

        //处理方式
        model.addAttribute("handleTypeList", HandleTypeEnum.getEnumList());

        //过站/生产设备
        modelService.getMesEquipmentPage(model);

        //过站员
        modelService.getManagerPage(model);

        //所属科室
        modelService.getDepList(model);

        //region 使用物料、出库明细
        //[1].取出出库单
        TransportPurchaseOutDTOQuery outDTOQuery = new TransportPurchaseOutDTOQuery();
        outDTOQuery.setParentId(0);
        outDTOQuery.setTableId(191);
        outDTOQuery.setRecordId(produceId);
        outDTOQuery.setStopFlag(0);
        TransportPurchaseOutDTO outDTO = purchaseOutService.getByQuery(outDTOQuery);

        //[2].取出出库明细
        if (outDTO != null) {
            TransportPurchaseDetailDTOQuery detailQuery = new TransportPurchaseDetailDTOQuery();
            detailQuery.setTableId(205);
            detailQuery.setPurId(outDTO.getId());
            detailQuery.setStopFlag(0);
            detailQuery.setPageSize(100);
            Page<TransportPurchaseDetailDTO> detailPage = purchaseDetailService.getForPage(detailQuery);
            for (TransportPurchaseDetailDTO item : detailPage.getItems()) {
                TransportPurchaseDTO dto = purchaseService.getFromCacheId(item.getPartId());
                if (dto != null) {
                    item.setPartName(dto.getPartName());
                    item.setPartNo(dto.getPartNo());
                    item.setSpecialName(dto.getSpecialName());
                }
            }
            model.addAttribute("partsDetailList", detailPage.getItems());
        }
        //endregion

        return "mes/passstation/edit";
    }
    //endregion

    //region 获取包信息

    /**
     * 获取包信息
     *
     * @param snCode sn码
     * @param passId 当前过站ID
     * @return map
     */
    @RequestMapping(value = "/getPackageInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> getPackageInfo(String snCode, Integer passId) {

        Map<Object, Object> map = new HashMap<>();
        map.put("returnCode", 0);

        if (StringUtils.isBlank(snCode)) {
            return map;
        }

        snCode = snCode.trim();

        //通过sn码获取包信息
        MesProducePackageDTO pkg = mesProducePackageService.getBySnCode(snCode);
        map.put("packageId", pkg.getId());
        map.put("packageName", pkg.getPackageName());
        map.put("snCode", snCode);
        map.put("startEndNumber", pkg.getStartNumber() + " ~ " + pkg.getEndNumber());

        //获取上一道工序过站的数量（因为上一站可能有不良品）
        map.put("passCount", pkg.getTotalCount());

        //历时
        String duration = "--";

        //过站类型：0入站/1出站
        int passType = 0;

        //获取最新的一条，有可能是已经过完站，也有可能只入了站
        MesProducePassStationDetailDTO detailDTO = mesProducePassStationDetailService.getByProducePkg(pkg.getProduceId(), pkg.getId());
        if (detailDTO != null) { //如果拆包、合包了，那么是获取不到信息的，这时只能以sn包的数量为主
            map.put("passCount", detailDTO.getGoodCount());

            if (detailDTO.getOutStationTimeSr().startsWith("1990-01-01")) {
                //说明已入站未出站，从入站时间开始算
                if (!detailDTO.getInStationTimeSr().equals("1990-01-01")) {
                    duration = DateUtils.getDistanceTime2(detailDTO.getInStationTimeSr(), DateUtils.getCurrTimeSr());
                    passType = 1;
                }
            } else {
                //已出站，从出站时间开始算
                duration = DateUtils.getDistanceTime2(detailDTO.getOutStationTimeSr(), DateUtils.getCurrTimeSr());

                if (passId.equals(detailDTO.getPassId())) {
                    passType = -1; //已经出过站，不能重复出站
                }
            }
        }
        map.put("duration", duration);
        map.put("passType", passType);

        map.put("returnCode", 1);
        return map;
    }
    //endregion

    //region 手动过站

    /**
     * 手动过站
     *
     * @param passId     过站ID
     * @param packageid  包ID
     * @param sncode     SN码
     * @param passcount  过站数量
     * @param goodcount  良品
     * @param badcount   不良品
     * @param defecttype 缺陷类型
     * @param handletype 处理方式
     * @param produceId  生产订单ID
     * @param equipId    设备ID
     * @param operator   过站员
     * @param state      0入站/1出站
     * @return map
     */
    @RequestMapping(value = "/goPassStation", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> goPassStation(Integer passId,
                                             Integer packageid,
                                             String sncode,
                                             Integer passcount,
                                             Integer goodcount,
                                             Integer badcount,
                                             Integer defecttype,
                                             Integer handletype,
                                             Integer produceId,
                                             Integer equipId,
                                             Integer operator,
                                             Integer state) {
        Map<Object, Object> map = new HashMap<>();
        map.put("returnCode", 0);
        map.put("returnMessage", "过站失败！");

        try {
            if (StringUtils.isBlank(sncode)) {
                map.put("returnMessage", "请输入过站信息！");
                return map;
            }

            if (passcount <= 0 || goodcount <= 0) {
                map.put("returnMessage", "请输入过站数量和良品数量！");
                return map;
            }

            if (equipId <= 0 || operator <= 0) {
                map.put("returnMessage", "请选择过站设备和过站员！");
                return map;
            }

            if (badcount > 0 && defecttype <= 0) {
                map.put("returnMessage", "请选择缺陷类型！");
                return map;
            }

            //region 是否已经过站，如果已过则更新，否则插入
            MesProducePassStationDetailDTOQuery existQuery = new MesProducePassStationDetailDTOQuery();
            existQuery.setPassId(passId);
            existQuery.setPackageId(packageid);
            MesProducePassStationDetailDTO existDTO = mesProducePassStationDetailService.getByQuery(existQuery);

            MesProducePassStationDetailDTO insert = new MesProducePassStationDetailDTO();
            insert.setProduceId(produceId);
            insert.setPassId(passId);
            insert.setPackageId(packageid);
            insert.setSnCode(sncode);
            insert.setPassCount(passcount);
            insert.setGoodCount(goodcount);
            insert.setBadCount(badcount);
            insert.setPassStatus(-1);
            insert.setDefectType(defecttype);
            insert.setHandleType(handletype);
            insert.setHandleResult(0);
            insert.setOperator(operator);
            if (state == 0) {
                insert.setInStationTime(new Date());
                insert.setOutStationTime(DateConvertUtils.strToDate("1990-01-01"));
            } else {
                insert.setOutStationTime(new Date());
            }
            insert.setDeleteFlag(0);

            if (existDTO == null) {
                mesProducePassStationDetailService.insert(insert);
            } else {
                insert.setId(existDTO.getId());
                mesProducePassStationDetailService.updateInfoById(insert);
            }
            //endregion

            //region 判断是否是最后一个包
            //判断依据：总包数 = 已过站包
            boolean isNextPkg = false;
            List<MesProducePackageDTO> packageList = mesProducePackageService.getListByProduceId(produceId);
            List<MesProducePassStationDetailDTO> stationDetailList = mesProducePassStationDetailService.getListByStationId(passId);

            if (packageList.size() == stationDetailList.size()) {
                isNextPkg = true;
            }

            //并且均已出站（出站日期没有1990-01-01的记录）
            for (MesProducePassStationDetailDTO ci : stationDetailList) {
                if (ci.getOutStationDateSr().equals("1990-01-01")) {
                    isNextPkg = false;
                    break;
                }
            }

            //endregion

            //region 更新过站信息中
            MesProducePassStationDTO origin = mesProducePassStationService.getById(passId);

            //良品率
            float _goodrate = 1f;

            if (origin != null) {
                MesProducePassStationDTO update = new MesProducePassStationDTO();
                update.setId(passId);

                //设备、人员
                update.setOperator(operator);
                update.setOperateTime(new Date());
                update.setEquipId(equipId);

                //已过站数量、良品、不良品、良品率
                update.setPassCount(origin.getPassCount() + passcount);
                update.setGoodCount(origin.getGoodCount() + goodcount);
                update.setBadCount(origin.getBadCount() + badcount);

                _goodrate = Float.parseFloat(update.getGoodCount() + "") / Float.parseFloat(update.getPassCount() + "");
                update.setGoodRate(new BigDecimal(_goodrate + ""));

                //如果是最后一个包，则更新过站状态
                if (isNextPkg) {
                    update.setPassStatus(1);
                }

                mesProducePassStationService.updateInfoById(update);

                //如果是最后一个包，则判断良品率是否低于标准，低则锁定
                if (isNextPkg) {
                    MesProduceWorkmanshipProcessDTO stadard = mesProduceWorkmanshipProcessService.getById(origin.getProcessId());
                    if (stadard != null && stadard.getLockGoodRate() == 1 && stadard.getLimitGoodRate().compareTo(new BigDecimal(_goodrate)) > 0) {
                        //锁定当前订单
                        mesProduceOrderService.changeState(origin.getProduceId(), 1);

                        MesProduceOrderDTO produceOrder = mesProduceOrderService.getById(origin.getProduceId());

                        //并且增加一条报警记录
                        String title = "工序（" + stadard.getProcessName() + "）低于标准良品率";
                        String content = "订单：" + produceOrder.getOrderName() + "<br/>";
                        content += "单号：" + produceOrder.getOrderCode() + "<br/>";
                        content += "工艺：" + mesProduceWorkmanshipService.getShipNane(stadard.getShipId()) + "<br/>";
                        content += "工序：" + stadard.getProcessName() + "<br/>";
                        content += "标准良品率不低于：" + stadard.getLimitGoodRate() + "<br/>";
                        content += "当前工序号良品率：<span class='text-danger'>" + _goodrate + "</span><br/>";
                        content += "操作：已<span class='text-danger'>锁定</span>该订单<br/>";
                        iotMessageService.sendMessage(title, content);
                    }
                }

            }
            //endregion

            map.put("returnMessage", "过站成功！");
            map.put("returnCode", 1);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return map;
    }
    //endregion

    //region 订单过站详情
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(HttpServletRequest request, Model model, Integer produceId) {

        //region 获取生产订单信息
        MesProduceOrderDTO produceObj = mesProduceOrderService.getById(produceId);
        if (produceObj == null) {
            throw new RuntimeException("未查询到生产订单信息");
        }
        produceObj.setShipName(modelService.getMesShipName(produceObj.getShipId()));
        produceObj.setProduceLineName(modelService.getMesProduceLineName(produceObj.getProduceLine()));
        produceObj.setMaterialReadyName(MaterialReadyEnum.getEnumByKey(produceObj.getMaterialReady()));
        produceObj.setOperatorCn(modelService.getManageName(produceObj.getOperator()));
        produceObj.setStatusName(OrderStatusEnum.getEnumByKey(produceObj.getStatus()));
        produceObj.setOrderTypeName(OrderTypeEnum.getEnumByKey(produceObj.getOrderType()));
        produceObj.setSnRuleName(QRCodeRuleEnum.getEnumByKey(produceObj.getSnRule()));
        model.addAttribute("produceObj", produceObj);
        //endregion

        //region 获取所有已过站工序记录
        MesProducePassStationDTOQuery passProcessQuery = new MesProducePassStationDTOQuery();
        passProcessQuery.setProduceId(produceId);
        passProcessQuery.setStopFlag(0);
        Page<MesProducePassStationDTO> passProcessPage = mesProducePassStationService.getForPage(passProcessQuery);
        for (MesProducePassStationDTO item : passProcessPage.getItems()) {
            item.setProcessName(modelService.getMesProcessName(item.getProcessId()));
            item.setEquipName(modelService.getMesEquipName(item.getEquipId()));
            item.setOperatorCn(modelService.getManageName(item.getOperator()));
            item.setDepName(modelService.getDepName(item.getDepId()));

            //获取过站详情
            List<MesProducePassStationDetailDTO> stationDetailList = mesProducePassStationDetailService.getListByStationId(item.getId());
            for (MesProducePassStationDetailDTO ci : stationDetailList) {
                MesProducePackageDTO pkg = mesProducePackageService.getById(ci.getPackageId());
                ci.setPackageName(pkg == null ? "" : pkg.getPackageName());
                ci.setDefectTypeName(modelService.getCatalogName(ci.getDefectType()));
                ci.setHandleTypeName(HandleTypeEnum.getEnumByKey(ci.getHandleType()));
                ci.setHandleResultName(HandleResultEnum.getEnumByKey(ci.getHandleResult()));
            }
            item.setPassDetailList(stationDetailList);
        }
        model.addAttribute("passProcessList", passProcessPage.getItems());
        //endregion

        //region 所有的工序都走完以后，显示完工按钮（并且未执行过完工操作）
        //当前状态：0新订单/1审核中/5已审核/10备料中/12生产中/15已暂停/20已完工/26测试中/28待发货/30已发货/35已完成/40已归档
        int canEndOperation = 0;

        if (produceObj.getStatus() < 20) {
            //[1].获取最新的一条过站信息（每道工序都会生成一条）
            MesProducePassStationDTO passStationObj = mesProducePassStationService.getByProduceId(produceId);
            if (passStationObj != null && passStationObj.getPassStatus() == 1) {
                //[2].获取最后一道工序
                MesProduceWorkmanshipProcessDTO processObj = mesProduceWorkmanshipProcessService.getLastProcess(passStationObj.getShipId());
                if (processObj != null && processObj.getId().equals(passStationObj.getProcessId())) {
                    //可以完工了
                    canEndOperation = 1;
                }
            }
        }

        model.addAttribute("canEndOperation", canEndOperation);
        //endregion

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"S-D-SCDD-WG"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "mes/passstation/detail";
    }
    //endregion
}